using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Web;
using System.Net;


namespace Rally_Dekstop
{
    public interface IRallyService
    {
        string DeleteTestCase(string testcaseID);
        ArrayList ValidateCredentials(object[] agrs);
        object[] GetWorkspaceType_Projects(string workspaceref);
        ArrayList GetTestCasePerWorkProduct(string workproduct, string id);
        ArrayList GetTestVerdicts(string workspaceref);
        Rally_Dekstop.TestCaseSpecifics GetTestCaseSpecifics(string workspaceref);
        Rally_Dekstop.DefectSpecifics GetDefectSpecifics(string workspaceref);
        TaskSpecifics GetTaskSpecifics(string workspaceref);
        string CreateTestResult(object[] args);
        string CreateTestCase(string projectref,string workproductref, string Owner, Rally_Dekstop.TestCase tcnew);
        string GetReference(string type, string id);
        ArrayList GetDefects(string queryString);
        ArrayList UpdatedDefects(string timestamp);
        byte[] GetAttachmentFromObjectID(string objectID);
        Hashtable GetTasks(string queryString);
        Hashtable UpdatedTasks(string timestamp);
        string UpdateDefect(Defect defect);
        void UpdateTask(Task task);
        string GetRevisions(string objectID);
        int ReturnNumberOfDefectsReOpened(string timestamp);
        int ReturnNumberOfDefectsReported(string timestamp);
        string CreateDefect(Defect defect);
        string UpdateTestCase(TestCase tc);
    }
    public class RallyAPIUseCase : IRallyService
    {
        RallyAPI_UseCase.RallyServiceService service = null;
        public string DeleteTestCase(string testcaseID)
        {
            StringBuilder resultString = new StringBuilder();
            
            try
            {
                int len = testcaseID.Length;
                string testRef = GetReference("testcase", testcaseID.Substring(2, len - 2));
                RallyAPI_UseCase.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UseCase.PersistableObject();
                persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.07/testcase/" + testRef;

                RallyAPI_UseCase.OperationResult result = service.delete(persisTableObj);
                
                if (result.Errors.Length > 0)
                {
                    resultString.Append(System.Environment.NewLine);
                    foreach (string str in result.Errors)
                    {
                        resultString.Append(str);
                        resultString.Append(System.Environment.NewLine);
                    }
                }


                
            }
            catch (Exception ee)
            {
                resultString.Append("Error occured: " + ee.Message);
            }
            
           return resultString.ToString();
            
        }
        public string GetReference(string type, string id)
        {
            try
            {
                
                string reference;
                if (RallyDesk.Cache.Contains(RallyDesk.CacheKey + type + id))
                {
                    reference = RallyDesk.Cache.Get(RallyDesk.CacheKey + type + id) as string;
                    return reference;
                
                }
                else
                {
                    RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                    workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                    
                    string objectType = type;
                    string queryString;    
                    if(type != "testfolder")
                        queryString = "(FormattedID = \"" + id + "\")";
                    else
                        queryString = "(Name = \"" + id + "\")";

                    string orderString = "CreationDate desc";

                    bool fetchFullObjects = true;

                    // paging information
                    long start = 1;
                    long pageSize = 100;
                    

                    // issue query
                    RallyAPI_UseCase.QueryResult queryResult = service.query(
                      workspace,
                      objectType,
                      queryString, orderString,
                      fetchFullObjects,
                      start, pageSize);

                    reference = Convert.ToString(queryResult.Results[0].ObjectID);
                    RallyDesk.Cache.Add(RallyDesk.CacheKey + type + id, reference);
                    return reference;
                }
            }
            catch (Exception)
            {

                return "False";

            }
            
}
        public RallyAPIUseCase(string url)
        {
            service = new Rally_Dekstop.RallyAPI_UseCase.RallyServiceService();
            if (url != string.Empty)
                service.Url = url;
            System.Net.NetworkCredential crediential = new System.Net.NetworkCredential(RallyDesk.Username, RallyDesk.Password);
            Uri uri = new Uri(service.Url);
            System.Net.ICredentials credentials = crediential.GetCredential(uri, "Basic");
            service.Credentials = credentials;
            service.PreAuthenticate = true;
            service.CookieContainer = new System.Net.CookieContainer();
        }
        public ArrayList ValidateCredentials(object[] args)
        {
            string username = args[0] as string;
            string password = args[1] as string;
            string hostname = args[2] as string;
            ArrayList result = new ArrayList();
            try
            {

                service.Url = "https://" + hostname + ".rallydev.com:443/slm/webservice/1.07/RallyService";
                System.Net.NetworkCredential crediential = new System.Net.NetworkCredential(username, password);
                Uri uri = new Uri(service.Url);
                System.Net.ICredentials credentials = crediential.GetCredential(uri, "Basic");
                service.Credentials = credentials;
                service.PreAuthenticate = true;
                service.CookieContainer = new System.Net.CookieContainer();

                RallyAPI_UseCase.WSObject rr = new Rally_Dekstop.RallyAPI_UseCase.WSObject();
                rr = service.getCurrentSubscription();


                int workspacecount = 0;
                object[] work = new object[2];

                workspacecount = ((Rally_Dekstop.RallyAPI_UseCase.Subscription)(rr)).Workspaces.Length;
                for (int i = 0; i < workspacecount; i++)
                {
                    //result.Add(((Rally_Dekstop.RallyAPI_UseCase.Subscription)(rr)).Workspaces[i].refObjectName);
                    //result.Add(((Rally_Dekstop.RallyAPI_UseCase.Subscription)(rr)).Workspaces[i].@ref);


                    result.Add(new string[2]);
                    ((string[])(result[i]))[0] = ((Rally_Dekstop.RallyAPI_UseCase.Subscription)(rr)).Workspaces[i].refObjectName;
                    ((string[])(result[i]))[1] = ((Rally_Dekstop.RallyAPI_UseCase.Subscription)(rr)).Workspaces[i].@ref;

                }
               // The request failed with HTTP status 503: Service Temporarily Unavailable.
            }
            catch (System.Net.WebException ex)
            {
                if (ex.Status.Equals(System.Net.WebExceptionStatus.ProtocolError))
                {
                    if (!(ex.Message.Equals("The request failed with HTTP status 401: Unauthorized.")))
                        throw;
                }
                else
                    throw;
            }
            catch (Exception )
            {
                throw;
            }
            return result;
        }
        public object[] GetWorkspaceType_Projects(string workspaceref)
        {
            try
            {
                Rally_Dekstop.Projects projects = new Projects();
                string workspacetype;

                object[] result = new object[2];

                RallyAPI_UseCase.Workspace workspace = new Rally_Dekstop.RallyAPI_UseCase.Workspace();
                //workspace.@ref = workspaceref;
                string objectType = "workspace";
                string queryString = "";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;

                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);

                workspacetype = ((Rally_Dekstop.RallyAPI_UseCase.Workspace)(queryResult.Results[0])).Style;

                int i =0;
                int projCount = ((Rally_Dekstop.RallyAPI_UseCase.Workspace)(queryResult.Results[0])).Projects.Length;
                for (i = 0; i < projCount; i++)
                {
                    projects.Project.Add(((Rally_Dekstop.RallyAPI_UseCase.WSObject)(((Rally_Dekstop.RallyAPI_UseCase.Workspace)(queryResult.Results[0])).Projects[i])).refObjectName);
                    projects.ProjectRef.Add(((Rally_Dekstop.RallyAPI_UseCase.WSObject)(((Rally_Dekstop.RallyAPI_UseCase.Workspace)(queryResult.Results[0])).Projects[i])).@ref);
                }

                result[0] = workspacetype;
                result[1] = projects;



                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public ArrayList GetTestCasePerWorkProduct(string workproduct, string id)
        {
            try
            {
                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "testcase";
                string idnum;
                int len;

                string WP_Ref = GetReference(workproduct, id);


                if (WP_Ref == "False")
                {
                    return null;
                }
                string queryString;

                if(workproduct != "testfolder")
                    queryString = "(WorkProduct = \"https://" + RallyDesk.HOSTNAME + ".rallydev.com:443/slm/webservice/1.07/" + workproduct + "/" + WP_Ref + "\")";
                else
                    queryString = "(TestFolder = \"https://" + RallyDesk.HOSTNAME + ".rallydev.com:443/slm/webservice/1.07/" + workproduct + "/" + WP_Ref + "\")";
                
                
                
                
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                ArrayList result = new ArrayList();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }
                    //myInt = condition ? 3 : 4;
                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            result.Add(new TestCase());
                           idnum =  ((TestCase)(result[resindex])).ID = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).FormattedID;
                            ((TestCase)(result[resindex])).TestRef = Convert.ToString(((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).ObjectID);
                            ((TestCase)(result[resindex])).Name = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Name;
                            ((TestCase)(result[resindex])).Description = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Description;
                            ((TestCase)(result[resindex])).Method = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Method;
                            ((TestCase)(result[resindex])).Notes = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Notes;
                            ((TestCase)(result[resindex])).Objective = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Objective;
                            ((TestCase)(result[resindex])).Package = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Package;
                            ((TestCase)(result[resindex])).PostConditions = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).PostConditions;
                            ((TestCase)(result[resindex])).PreConditions = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).PreConditions;
                            ((TestCase)(result[resindex])).Priority = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Priority;
                            ((TestCase)(result[resindex])).Type = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Type;
                            ((TestCase)(result[resindex])).ValidationExpectedResult = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).ValidationExpectedResult;
                            ((TestCase)(result[resindex])).ValidationInput = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).ValidationInput;
                            ((TestCase)(result[resindex])).Risk = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Risk;
                            ((TestCase)(result[resindex])).Owner = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).Owner;
                            ((TestCase)(result[resindex])).LastBuild = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).LastBuild;
                            ((TestCase)(result[resindex])).LastVerdict = ((Rally_Dekstop.RallyAPI_UseCase.TestCase)(queryResult.Results[i])).LastVerdict;

                            len = idnum.Length;
                            if(!RallyDesk.Cache.Contains(RallyDesk.CacheKey + "testcase" + idnum.Substring(2, len - 2)))
                                RallyDesk.Cache.Add(RallyDesk.CacheKey + "testcase" + idnum.Substring(2, len - 2),((TestCase)(result[resindex])).TestRef);                           
                                
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public ArrayList GetTestVerdicts(string workspaceref)
        {
            try
            {

                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Test Case Result\")";//"(Name = \"Test Case\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);

                ArrayList verdicts = new ArrayList();
                int recordcount = ((Rally_Dekstop.RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((Rally_Dekstop.RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Verdict")
                    {
                        verdictcount = ((Rally_Dekstop.RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            verdicts.Add(((Rally_Dekstop.RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }


                    }
                }





                return verdicts;
            }
            catch (Exception)
            {
                return null;

            }

        }
        public Rally_Dekstop.TestCaseSpecifics GetTestCaseSpecifics(string workspaceref)
        {
            try
            {
                Rally_Dekstop.TestCaseSpecifics tc = new Rally_Dekstop.TestCaseSpecifics();
                RallyAPI_UseCase.Workspace workspace = new Rally_Dekstop.RallyAPI_UseCase.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Test Case\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);


                int recordcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Type")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Types.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Priority")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Priority.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Method")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Method.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Risk")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Risk.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Package")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Package.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                }
                return tc;

            }
            catch (Exception)
            {
                return null;

            }

        }
        public Rally_Dekstop.DefectSpecifics GetDefectSpecifics(string workspaceref)
        {
            try
            {
                Rally_Dekstop.DefectSpecifics tc = new Rally_Dekstop.DefectSpecifics();
                RallyAPI_UseCase.Workspace workspace = new Rally_Dekstop.RallyAPI_UseCase.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Defect\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);


                int recordcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Environment")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Environments.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Priority")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Priorities.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Resolution")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Resolutions.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Severity")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Severities.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "State")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.States.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "SubmittedBy")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Users.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                }
                return tc;

            }
            catch (Exception)
            {
                return null;

            }
        }
        public TaskSpecifics GetTaskSpecifics(string workspaceref)
        {
            try
            {
                TaskSpecifics tc = new TaskSpecifics();
                RallyAPI_UseCase.Workspace workspace = new Rally_Dekstop.RallyAPI_UseCase.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Task\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);


                int recordcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "State")
                    {
                        verdictcount = ((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.States.Add(((RallyAPI_UseCase.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                   
                }
                return tc;

            }
            catch (Exception)
            {
                return null;

            }
        }
        public string CreateTestResult(object[] args)
        {
            string TestCaseID = args[0] as string;
            string Verdict = args[1] as string;
            string Tester = args[2] as string;
            string Build = args[3] as string;
            string Notes = args[4] as string;
            string TestCaseRef = args[5] as string;
            string WorkspaceRef = args[6] as string;
            
            try
            {
                RallyAPI_UseCase.Workspace ws = new Rally_Dekstop.RallyAPI_UseCase.Workspace();
                ws.@ref = WorkspaceRef;
                string formattedID;
                int len = TestCaseID.Length;
                formattedID = TestCaseID.Substring(2, len - 2);
                if (TestCaseRef == string.Empty)
                    TestCaseRef = GetReference("testcase", formattedID);
                if (TestCaseRef == "False")
                {
                    return "Could not get Test Case Reference";
                }

                RallyAPI_UseCase.TestCase testCase = new RallyAPI_UseCase.TestCase();
                testCase.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/testcase/" + Convert.ToString(TestCaseRef);


                RallyAPI_UseCase.TestCaseResult testCaseResult = new Rally_Dekstop.RallyAPI_UseCase.TestCaseResult();
                testCaseResult.TestCase = testCase;
                testCaseResult.Workspace = ws;

                // Result date is required
                testCaseResult.Date = System.DateTime.Now;
                testCaseResult.DateSpecified = true; // see above in unresolved issues

                // Verdict is required
                testCaseResult.Verdict = Verdict;
                testCaseResult.Tester = Tester;
                // Build number is required
                testCaseResult.Build = Build;
                testCaseResult.Notes = Notes;
                // Create the test case result on the server
                RallyAPI_UseCase.CreateResult createResult = service.create(testCaseResult);
                if (createResult.Errors.Length > 0)
                    return createResult.Errors[0];
                else
                    return string.Empty;
            }
            catch (Exception ee)
            {
                return ee.Message;

            }
        }
        public string CreateTestCase(string projectref,string workproductref, string Owner, Rally_Dekstop.TestCase tcnew)
        {
            try
            {
                RallyAPI_UseCase.TestCase testCase = new Rally_Dekstop.RallyAPI_UseCase.TestCase();
                testCase.Name = tcnew.Name;
                testCase.Description = tcnew.Description;
                testCase.Notes = tcnew.Notes;
                testCase.Owner = Owner;
                testCase.Objective = tcnew.Objective;
                testCase.Type = tcnew.Type;
                testCase.Method = tcnew.Method;
                testCase.Priority = tcnew.Priority;
                testCase.Risk = tcnew.Risk;
                testCase.Package = tcnew.Package;
                testCase.PreConditions = tcnew.PreConditions;
                testCase.PostConditions = tcnew.PostConditions;
                testCase.ValidationInput = tcnew.ValidationInput;
                testCase.ValidationExpectedResult = tcnew.ValidationExpectedResult;
                

                RallyAPI_UseCase.Workspace ws = new Rally_Dekstop.RallyAPI_UseCase.Workspace();
                ws.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                testCase.Workspace = ws;

                RallyAPI_UseCase.Project ProjS = new Rally_Dekstop.RallyAPI_UseCase.Project();
                ProjS.@ref = projectref;
                testCase.Project = ProjS;

                //set ref to workproduct
                RallyAPI_UseCase.Artifact wk = new RallyAPI_UseCase.Artifact();
                wk.@ref = workproductref;
                testCase.WorkProduct = wk;
                
                RallyAPI_UseCase.CreateResult createResult = service.create(testCase);

                if (createResult.Errors.Length > 0)
                    return createResult.Errors[0];
                else
                    return string.Empty;
                
            }
            catch (Exception ee)
            {
                return ee.Message;

            }
        }
        public ArrayList GetDefects(string queryString)
        {
            try
            {
                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "defect";


                //string queryString = "(ObjectID = \"" + RallyDesk.Username + "\")";
                
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                ArrayList result = new ArrayList();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                           
                            Defect defect = new Defect();

                            defect.ID = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).FormattedID;
                            defect.Owner = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Owner;
                            defect.Name = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Name;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Notes;
                            defect.Resolution = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Resolution;
                            defect.Severity = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Severity;
                            defect.Priority = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Priority;
                            defect.State = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).State;
                            defect.SubmittedBy = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).SubmittedBy;
                            defect.VerifiedIn = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).VerifiedInBuild;
                            defect.Environment = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Environment;
                            defect.ReleaseNote = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).ReleaseNote;
                            defect.Description = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Description;                            
                            defect.DefectRef = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).ObjectID.ToString();

                            defect.Project = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Project.@ref;
                            if (((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Requirement != null)
                            {
                                defect.Requirement.Name = ((Rally_Dekstop.RallyAPI_UseCase.WSObject)(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Requirement)).refObjectName;
                                defect.Requirement.Reference = ((Rally_Dekstop.RallyAPI_UseCase.WSObject)(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Requirement)).@ref;
                            }
                            //((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Requirement.

                            defect.TargetBuild = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).TargetBuild;

                            if(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).TargetDate != null)
                                defect.TargetDate = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).TargetDate.ToString();

                            defect.FixedIn = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).FixedInBuild;
                            defect.FoundIn = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).FoundInBuild;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Notes;
                            defect.RevisionHistoryID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UseCase.WSObject)((((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i]))).RevisionHistory)).@ref);

                            if (((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments[j].@ref;
                                    defect.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }
                            result.Add(defect);
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public ArrayList UpdatedDefects(string timestamp)
        {
            try
            {
                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "defect";


                string queryString = "((LastUpdateDate >= \"" + timestamp + "\") or (CreationDate >= \"" + timestamp + "\")) ";
                
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                ArrayList result = new ArrayList();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                           
                            Defect defect = new Defect();

                            defect.ID = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).FormattedID;
                            defect.Owner = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Owner;
                            defect.Name = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Name;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Notes;
                            defect.Resolution = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Resolution;
                            defect.Severity = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Severity;
                            defect.Priority = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Priority;
                            defect.State = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).State;
                            defect.SubmittedBy = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).SubmittedBy;
                            defect.VerifiedIn = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).VerifiedInBuild;
                            defect.Environment = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Environment;
                            defect.ReleaseNote = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).ReleaseNote;
                            defect.Description = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Description;                            
                            defect.DefectRef = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).ObjectID.ToString();
                            defect.Project = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Project.@ref;

                            if (((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Requirement != null)
                            {
                                
                                    defect.Requirement.Name = ((Rally_Dekstop.RallyAPI_UseCase.WSObject)(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Requirement)).refObjectName;
                                    defect.Requirement.Reference = ((Rally_Dekstop.RallyAPI_UseCase.WSObject)(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Requirement)).@ref;
                               
                            
                            }
                            defect.TargetBuild = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).TargetBuild;

                            if(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).TargetDate != null)
                                defect.TargetDate = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).TargetDate.ToString();

                            defect.FixedIn = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).FixedInBuild;
                            defect.FoundIn = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).FoundInBuild;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Notes;
                            defect.RevisionHistoryID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UseCase.WSObject)((((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i]))).RevisionHistory)).@ref);

                            if (((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UseCase.Defect)(queryResult.Results[i])).Attachments[j].@ref;
                                    defect.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }
                            result.Add(defect);
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public byte[] GetAttachmentFromObjectID(string objectID)
        {
           
            RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;                

            RallyAPI_UseCase.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UseCase.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/attachment/" + objectID;

            RallyAPI_UseCase.WSObject attachment = service.read(persisTableObj);

            return ((RallyAPI_UseCase.Attachment)attachment).Content.Content;

            
        }
        public Hashtable GetTasks(string queryString)
        {
            try
            {
                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "task";


                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                Hashtable result = new Hashtable();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            Task tsk = new Task();
                            tsk.ID = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).FormattedID;
                            tsk.Owner = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Owner;
                            tsk.Name = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Name;
                            tsk.Notes = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Notes;
                            tsk.Actuals = Convert.ToString(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Actuals);
                            tsk.Blocked = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Blocked;
                            tsk.Description = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Description;
                            tsk.Estimate = Convert.ToString(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Estimate);
                            tsk.Project = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Project.@ref;
                            tsk.State = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).State;
                            tsk.StoryCard = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Card.FormattedID;
                            tsk.StoryCardRef = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Card.@ref;
                            tsk.ToDO = Convert.ToString(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).ToDo);
                            tsk.TaskRef = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).@ref;
                            
                            if (((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments[j].@ref;
                                    tsk.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }

                            result.Add(tsk.ID, tsk);
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public Hashtable UpdatedTasks(string timestamp)
        {
            try
            {
                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "task";

                string queryString = "(LastUpdateDate >= \"" + timestamp + "\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                Hashtable result = new Hashtable();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);


                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            Task tsk = new Task();
                            tsk.ID = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).FormattedID;
                            tsk.Owner = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Owner;
                            tsk.Name = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Name;
                            tsk.Notes = ((Rally_Dekstop.RallyAPI_UseCase.Artifact)(queryResult.Results[i])).Notes;
                            tsk.Actuals = Convert.ToString(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Actuals);
                            tsk.Blocked = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Blocked;
                            tsk.Description = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Description;
                            tsk.Estimate = Convert.ToString(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Estimate);
                            tsk.Project = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Project.@ref;
                            tsk.State = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).State;
                            tsk.StoryCard = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Card.@ref;
                            tsk.ToDO = Convert.ToString(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).ToDo);
                            tsk.TaskRef = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).@ref;

                            if (((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UseCase.Task)(queryResult.Results[i])).Attachments[j].@ref;
                                    tsk.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }

                            result.Add(tsk.ID, tsk);
                           
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public string UpdateDefect(Defect defect)
        {
            RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UseCase.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UseCase.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/defect/" + defect.DefectRef;

            RallyAPI_UseCase.WSObject currentDefect = service.read(persisTableObj);            

            ((RallyAPI_UseCase.Defect)currentDefect).Name = defect.Name;
            ((RallyAPI_UseCase.Defect)currentDefect).Notes = defect.Notes;
            ((RallyAPI_UseCase.Defect)currentDefect).Owner = defect.Owner;
            ((RallyAPI_UseCase.Defect)currentDefect).ReleaseNote = defect.ReleaseNote;

           // if(((RallyAPI_UseCase.Defect)currentDefect).Requirement != null)
           // ((RallyAPI_UseCase.Defect)currentDefect).Requirement.@ref = defect.Requirement.Reference;

            ((RallyAPI_UseCase.Defect)currentDefect).Resolution = defect.Resolution;
            ((RallyAPI_UseCase.Defect)currentDefect).Severity = defect.Severity;
            ((RallyAPI_UseCase.Defect)currentDefect).Priority = defect.Priority;
            ((RallyAPI_UseCase.Defect)currentDefect).State = defect.State;
            ((RallyAPI_UseCase.Defect)currentDefect).SubmittedBy = defect.SubmittedBy;
            ((RallyAPI_UseCase.Defect)currentDefect).TargetBuild = defect.TargetBuild;
            ((RallyAPI_UseCase.Defect)currentDefect).Description = defect.Description;
            ((RallyAPI_UseCase.Defect)currentDefect).Environment = defect.Environment;
            ((RallyAPI_UseCase.Defect)currentDefect).FixedInBuild = defect.FixedIn;
            ((RallyAPI_UseCase.Defect)currentDefect).FoundInBuild = defect.FoundIn;

             RallyAPI_UseCase.OperationResult result = service.update((RallyAPI_UseCase.PersistableObject)currentDefect);
             StringBuilder resultString = new StringBuilder();
            
             if (result.Errors.Length > 0)
             {
                 resultString.Append(System.Environment.NewLine);
                 foreach (string str in result.Errors)
                 {
                     resultString.Append(str);
                     resultString.Append(System.Environment.NewLine);
                 }
             }


             return resultString.ToString();

        }
        public void UpdateTask(Task task)
        {
            RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UseCase.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UseCase.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/defect/" + task.TaskRef;

            RallyAPI_UseCase.WSObject currentTask = service.read(persisTableObj);

            ((RallyAPI_UseCase.Task)currentTask).Name = task.Name;
            ((RallyAPI_UseCase.Task)currentTask).Notes = task.Notes;
            ((RallyAPI_UseCase.Task)currentTask).Owner = task.Owner;
            ((RallyAPI_UseCase.Task)currentTask).State = task.State;
            ((RallyAPI_UseCase.Task)currentTask).ToDo = Convert.ToDouble(task.ToDO);
            ((RallyAPI_UseCase.Task)currentTask).Actuals = Convert.ToDouble(task.Actuals);
            ((RallyAPI_UseCase.Task)currentTask).Blocked = task.Blocked;
            ((RallyAPI_UseCase.Task)currentTask).Description = task.Description;
            ((RallyAPI_UseCase.Task)currentTask).Estimate = Convert.ToDouble(task.Estimate);
           
            service.update((RallyAPI_UseCase.PersistableObject)currentTask);
          
        }
        public string CreateDefect(Defect defect)
        {
            RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UseCase.Project project = new Rally_Dekstop.RallyAPI_UseCase.Project();
            project.@ref = RallyDesk.CURRENTWORKSPACE.SelectedProjectRef;

            RallyAPI_UseCase.Defect currentDefect = new Rally_Dekstop.RallyAPI_UseCase.Defect();

            currentDefect.Workspace = workspace;
            currentDefect.Project = project;

            ((RallyAPI_UseCase.Defect)currentDefect).Name = defect.Name;
            ((RallyAPI_UseCase.Defect)currentDefect).Notes = defect.Notes;
            ((RallyAPI_UseCase.Defect)currentDefect).Owner = defect.Owner;
            ((RallyAPI_UseCase.Defect)currentDefect).ReleaseNote = defect.ReleaseNote;

            if (!string.IsNullOrEmpty(defect.Requirement.Reference))
                ((RallyAPI_UseCase.Defect)currentDefect).Requirement.@ref = defect.Requirement.Reference;
            
            ((RallyAPI_UseCase.Defect)currentDefect).Resolution = defect.Resolution;
            ((RallyAPI_UseCase.Defect)currentDefect).Severity = defect.Severity;
            ((RallyAPI_UseCase.Defect)currentDefect).Priority = defect.Priority;
            ((RallyAPI_UseCase.Defect)currentDefect).State = defect.State;
            ((RallyAPI_UseCase.Defect)currentDefect).SubmittedBy = defect.SubmittedBy;
            ((RallyAPI_UseCase.Defect)currentDefect).TargetBuild = defect.TargetBuild;
            ((RallyAPI_UseCase.Defect)currentDefect).Description = defect.Description;
            ((RallyAPI_UseCase.Defect)currentDefect).Environment = defect.Environment;
            ((RallyAPI_UseCase.Defect)currentDefect).FixedInBuild = defect.FixedIn;
            ((RallyAPI_UseCase.Defect)currentDefect).FoundInBuild = defect.FoundIn;

            RallyAPI_UseCase.CreateResult result = service.create((RallyAPI_UseCase.PersistableObject)currentDefect);

            StringBuilder resultString = new StringBuilder();

            if (result.Errors.Length > 0)
            {
                resultString.Append(System.Environment.NewLine);
                foreach (string str in result.Errors)
                {
                    resultString.Append(str);
                    resultString.Append(System.Environment.NewLine);
                }
            }
            

            return resultString.ToString();

        }
        public string GetRevisions(string objectID)
        {
            string htmlRevisionsText = "<html> <font size=\"3\" face=\"Calibri\">";
            RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UseCase.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UseCase.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/revisionhistory/" + objectID;

            RallyAPI_UseCase.WSObject currentRevisionHistory = service.read(persisTableObj);
            
            
            for(int i =((RallyAPI_UseCase.RevisionHistory)currentRevisionHistory).Revisions.Length -1; i >= 0 ; i--) 
            {
                htmlRevisionsText = htmlRevisionsText + " <p> " + ((RallyAPI_UseCase.RevisionHistory)currentRevisionHistory).Revisions[i].Description + "<b> [ " + ((RallyAPI_UseCase.RevisionHistory)currentRevisionHistory).Revisions[i].User + " ] </b>" + " </p> ";
            }

            htmlRevisionsText = htmlRevisionsText + " </font></html>";

            return htmlRevisionsText;
        }
        public int ReturnNumberOfDefectsReOpened(string timestamp)
        {
            try
            {
                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "revision";
                
               string  queryString = "(((CreationDate > \"" + timestamp + "\") and (Description contains \"to [Re-Open]\")) and (User = \"" + RallyDesk.Username + "\"))";

              
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;

                int result=0;
                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                   1, pageSize);

                result = queryResult.Results.Length;

               

               

                return result;
            }
            catch (Exception)
            {
                return -1;

            }
        }
        public int ReturnNumberOfDefectsReported(string timestamp)
        {
            try
            {
                RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "defect";

                string queryString = "((CreationDate > \"" + timestamp + "\") and (SubmittedBy = \"" + RallyDesk.Username + "\"))";


                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;

                int result = 0;
                // issue query
                RallyAPI_UseCase.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                   1, pageSize);

                result = queryResult.Results.Length;





                return result;
            }
            catch (Exception)
            {
                return -1;

            }
        }
        public string UpdateTestCase(TestCase tc)
        {
            if (tc.TestRef == string.Empty)
            {
                tc.TestRef = GetReference("testcase", tc.ID);
            }


            RallyAPI_UseCase.Workspace workspace = new RallyAPI_UseCase.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UseCase.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UseCase.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/testcase/" + tc.TestRef;

            RallyAPI_UseCase.WSObject currentTestCase = service.read(persisTableObj);

            ((RallyAPI_UseCase.TestCase)currentTestCase).Name = tc.Name;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Notes = tc.Notes;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Objective = tc.Objective;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Type = tc.Type;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Method = tc.Method;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Priority = tc.Priority;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Risk = tc.Risk;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Package = tc.Package;
            ((RallyAPI_UseCase.TestCase)currentTestCase).PreConditions = tc.PreConditions;
            ((RallyAPI_UseCase.TestCase)currentTestCase).PostConditions = tc.PostConditions;
            ((RallyAPI_UseCase.TestCase)currentTestCase).Description = tc.Description;
            
            ((RallyAPI_UseCase.TestCase)currentTestCase).ValidationInput = tc.ValidationInput;
            ((RallyAPI_UseCase.TestCase)currentTestCase).ValidationExpectedResult = tc.ValidationExpectedResult;

             RallyAPI_UseCase.OperationResult result = service.update((RallyAPI_UseCase.PersistableObject)currentTestCase);
             StringBuilder resultString = new StringBuilder();
            
             if (result.Errors.Length > 0)
             {
                 resultString.Append(System.Environment.NewLine);
                 foreach (string str in result.Errors)
                 {
                     resultString.Append(str);
                     resultString.Append(System.Environment.NewLine);
                 }
             }


             return resultString.ToString();

        
        }
    }
    public class RallyAPIUserStory : IRallyService
    {
        RallyAPI_UserStory.RallyServiceService service = null;
        public string DeleteTestCase(string testcaseID)
        {
            StringBuilder resultString = new StringBuilder();

            try
            {
                int len = testcaseID.Length;
                string testRef = GetReference("testcase", testcaseID.Substring(2, len - 2));
                RallyAPI_UserStory.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UserStory.PersistableObject();
                persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.07/testcase/" + testRef;

                RallyAPI_UserStory.OperationResult result = service.delete(persisTableObj);

                if (result.Errors.Length > 0)
                {
                    resultString.Append(System.Environment.NewLine);
                    foreach (string str in result.Errors)
                    {
                        resultString.Append(str);
                        resultString.Append(System.Environment.NewLine);
                    }
                }



            }
            catch (Exception ee)
            {
                resultString.Append("Error occured: " + ee.Message);
            }
            
                return resultString.ToString();
            
        }
        public string GetReference(string type, string id)
        {
            try
            {
                string reference;
                if (RallyDesk.Cache.Contains(RallyDesk.CacheKey + type + id))
                {
                    reference = RallyDesk.Cache.Get(RallyDesk.CacheKey + type + id) as string;
                    return reference;

                }
                else
                {
                    RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                    workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                    
                    string objectType = type;

                   
                    string queryString;
                    if (type != "testfolder")
                        queryString = "(FormattedID = \"" + id + "\")";
                    else
                        queryString = "(Name = \"" + id + "\")";

                    string orderString = "CreationDate desc";

                    bool fetchFullObjects = true;

                    // paging information
                    long start = 1;
                    long pageSize = 100;


                    // issue query
                    RallyAPI_UserStory.QueryResult queryResult = service.query(
                      workspace,
                      objectType,
                      queryString, orderString,
                      fetchFullObjects,
                      start, pageSize);

                    reference = Convert.ToString(queryResult.Results[0].ObjectID);
                    RallyDesk.Cache.Add(RallyDesk.CacheKey + type + id, reference);
                    return reference;
                }
            }
            catch (Exception)
            {

                return "False";

            }





        }
        public RallyAPIUserStory(string url)
        {
            service = new Rally_Dekstop.RallyAPI_UserStory.RallyServiceService();
            if (url != string.Empty)
            service.Url = url;
            System.Net.NetworkCredential crediential = new System.Net.NetworkCredential(RallyDesk.Username, RallyDesk.Password);
            Uri uri = new Uri(service.Url);
            System.Net.ICredentials credentials = crediential.GetCredential(uri, "Basic");
            service.Credentials = credentials;
            service.PreAuthenticate = true;
            service.CookieContainer = new System.Net.CookieContainer();
        }
        public ArrayList ValidateCredentials(object[] args)
        {
            string username = args[0] as string;
            string password = args[1] as string;
            string hostname = args[2] as string;
            ArrayList result = null;
            try
            {

                service.Url = "https://" + hostname + ".rallydev.com:443/slm/webservice/1.07/RallyService";
                System.Net.NetworkCredential crediential = new System.Net.NetworkCredential(username, password);
                Uri uri = new Uri(service.Url);
                System.Net.ICredentials credentials = crediential.GetCredential(uri, "Basic");
                service.Credentials = credentials;
                service.PreAuthenticate = true;
                service.CookieContainer = new System.Net.CookieContainer();

                RallyAPI_UserStory.WSObject rr = new Rally_Dekstop.RallyAPI_UserStory.WSObject();
                rr = service.getCurrentSubscription();
                result.Add("true");
            }
            catch (System.Net.WebException ex)
            {
                if(!(ex.Status.Equals(System.Net.WebExceptionStatus.ProtocolError)))
                    throw;
            }
            catch(Exception )
            {   
                throw;
            }
            return result;
        }
        public object[] GetWorkspaceType_Projects(string workspaceref)
        {
            try
            {
                Rally_Dekstop.Projects projects = new Projects();
                string workspacetype;

                object[] result = new object[2];

                RallyAPI_UserStory.Workspace workspace = new Rally_Dekstop.RallyAPI_UserStory.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "workspace";
                string queryString = "";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);

                workspacetype = ((Rally_Dekstop.RallyAPI_UserStory.Workspace)(queryResult.Results[0])).Style;

                int i = 0;
                int projCount = ((Rally_Dekstop.RallyAPI_UserStory.Workspace)(queryResult.Results[0])).Projects.Length;
                for (i = 0; i < projCount; i++)
                {
                    projects.Project.Add(((Rally_Dekstop.RallyAPI_UserStory.WSObject)(((Rally_Dekstop.RallyAPI_UserStory.Workspace)(queryResult.Results[0])).Projects[i])).refObjectName);
                    projects.ProjectRef.Add(((Rally_Dekstop.RallyAPI_UserStory.WSObject)(((Rally_Dekstop.RallyAPI_UserStory.Workspace)(queryResult.Results[0])).Projects[i])).@ref);
                }

                result[0] = workspacetype;
                result[1] = projects;



                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public ArrayList GetTestCasePerWorkProduct(string workproduct, string id)
        {
            try
            {
                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "testcase";
                string idnum;
                int len;

                string WP_Ref = GetReference(workproduct, id);


                if (WP_Ref == "False")
                {
                    return null;
                }

                string queryString;
                if (workproduct != "testfolder")
                    queryString = "(WorkProduct = \"https://" + RallyDesk.HOSTNAME + ".rallydev.com:443/slm/webservice/1.07/" + workproduct + "/" + WP_Ref + "\")";
                else
                    queryString = "(TestFolder = \"https://" + RallyDesk.HOSTNAME + ".rallydev.com:443/slm/webservice/1.07/" + workproduct + "/" + WP_Ref + "\")";
                
                
                
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                ArrayList result = new ArrayList();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            result.Add(new TestCase());
                            idnum = ((TestCase)(result[resindex])).ID = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).FormattedID;
                            ((TestCase)(result[resindex])).TestRef = Convert.ToString(((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).ObjectID);
                            ((TestCase)(result[resindex])).Name = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Name;
                            ((TestCase)(result[resindex])).Description = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Description;
                            ((TestCase)(result[resindex])).Method = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Method;
                            ((TestCase)(result[resindex])).Notes = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Notes;
                            ((TestCase)(result[resindex])).Objective = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Objective;
                            ((TestCase)(result[resindex])).Package = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Package;
                            ((TestCase)(result[resindex])).PostConditions = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).PostConditions;
                            ((TestCase)(result[resindex])).PreConditions = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).PreConditions;
                            ((TestCase)(result[resindex])).Priority = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Priority;
                            ((TestCase)(result[resindex])).Type = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Type;
                            ((TestCase)(result[resindex])).ValidationExpectedResult = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).ValidationExpectedResult;
                            ((TestCase)(result[resindex])).ValidationInput = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).ValidationInput;
                            ((TestCase)(result[resindex])).Risk = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Risk;
                            ((TestCase)(result[resindex])).Owner = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).Owner;
                            ((TestCase)(result[resindex])).LastBuild = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).LastBuild;
                            ((TestCase)(result[resindex])).LastVerdict = ((Rally_Dekstop.RallyAPI_UserStory.TestCase)(queryResult.Results[i])).LastVerdict;

                            len = idnum.Length;
                            if (!RallyDesk.Cache.Contains(RallyDesk.CacheKey + "testcase" + idnum.Substring(2, len - 2)))
                                RallyDesk.Cache.Add(RallyDesk.CacheKey + "testcase" + idnum.Substring(2, len - 2), ((TestCase)(result[resindex])).TestRef);                           
                            
                            resindex++;

                        }



                      queryResult = service.query(
                      workspace,
                      objectType,
                      queryString, orderString,
                      fetchFullObjects,
                      resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public ArrayList GetTestVerdicts(string workspaceref)
        {
            try
            {

                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Test Case Result\")";//"(Name = \"Test Case\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);

                ArrayList verdicts = new ArrayList();
                int recordcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Verdict")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            verdicts.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }


                    }
                }





                return verdicts;
            }
            catch (Exception)
            {
                return null;

            }

        }
        public Rally_Dekstop.TestCaseSpecifics GetTestCaseSpecifics(string workspaceref)
        {
            try
            {
                Rally_Dekstop.TestCaseSpecifics tc = new Rally_Dekstop.TestCaseSpecifics();
                RallyAPI_UserStory.Workspace workspace = new Rally_Dekstop.RallyAPI_UserStory.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Test Case\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);


                int recordcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Type")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Types.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Priority")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Priority.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Method")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Method.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Risk")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Risk.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Package")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Package.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                }
                return tc;

            }
            catch (Exception)
            {
                return null;

            }

        }
        public Rally_Dekstop.DefectSpecifics GetDefectSpecifics(string workspaceref)
        {
            try
            {
                Rally_Dekstop.DefectSpecifics tc = new Rally_Dekstop.DefectSpecifics();
                RallyAPI_UserStory.Workspace workspace = new Rally_Dekstop.RallyAPI_UserStory.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Defect\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);


                int recordcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Environment")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Environments.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Priority")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Priorities.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Resolution")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Resolutions.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "Severity")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Severities.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "State")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.States.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "SubmittedBy")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.Users.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                }
                return tc;

            }
            catch (Exception)
            {
                return null;

            }
        }
        public TaskSpecifics GetTaskSpecifics(string workspaceref)
        {
            try
            {
                TaskSpecifics tc = new TaskSpecifics();
                RallyAPI_UserStory.Workspace workspace = new Rally_Dekstop.RallyAPI_UserStory.Workspace();
                workspace.@ref = workspaceref;
                string objectType = "typedefinition";
                string queryString = "(Name = \"Task\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;
                // paging information
                long start = 1;
                long pageSize = 100;


                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  start, pageSize);


                int recordcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes.Length;
                int iterate = 0;
                int iterateVerdicts = 0;
                int verdictcount = 0;

                for (iterate = 0; iterate < recordcount; iterate++)
                {
                    if (((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].ElementName == "State")
                    {
                        verdictcount = ((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues.Length;

                        for (iterateVerdicts = 0; iterateVerdicts < verdictcount; iterateVerdicts++)
                        {
                            tc.States.Add(((RallyAPI_UserStory.TypeDefinition)(queryResult.Results[0])).Attributes[iterate].AllowedValues[iterateVerdicts].StringValue);
                        }
                        iterateVerdicts = 0;

                    }

                }
                return tc;

            }
            catch (Exception)
            {
                return null;

            }
        }
        public string CreateTestResult(object[] args)
        {
            string TestCaseID = args[0] as string;
            string Verdict = args[1] as string;
            string Tester = args[2] as string;
            string Build = args[3] as string;
            string Notes = args[4] as string;
            string TestCaseRef = args[5] as string;
            string WorkspaceRef = args[6] as string;

            try
            {
                RallyAPI_UserStory.Workspace ws = new Rally_Dekstop.RallyAPI_UserStory.Workspace();
                ws.@ref = WorkspaceRef;
                string formattedID;
                int len = TestCaseID.Length;
                formattedID = TestCaseID.Substring(2, len - 2);
                if (TestCaseRef == string.Empty)
                    TestCaseRef = GetReference("testcase", formattedID);
                if (TestCaseRef == "False")
                {
                    return "Could not get Test Case Reference";
                }

                RallyAPI_UserStory.TestCase testCase = new RallyAPI_UserStory.TestCase();
                testCase.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/testcase/" + Convert.ToString(TestCaseRef);


                RallyAPI_UserStory.TestCaseResult testCaseResult = new Rally_Dekstop.RallyAPI_UserStory.TestCaseResult();

                testCaseResult.Workspace = ws;
                testCaseResult.TestCase = testCase;
                // Result date is required
                testCaseResult.Date = System.DateTime.Now;
                testCaseResult.DateSpecified = true; // see above in unresolved issues

                // Verdict is required
                testCaseResult.Verdict = Verdict;
                testCaseResult.Tester = Tester;
                // Build number is required
                testCaseResult.Build = Build;
                testCaseResult.Notes = Notes;
                // Create the test case result on the server
                RallyAPI_UserStory.CreateResult createResult = service.create(testCaseResult);

                if (createResult.Errors.Length > 0)
                    return createResult.Errors[0];
                else
                    return string.Empty;
            }
            catch (Exception ee)
            {
                return ee.Message;

            }
        }
        public string CreateTestCase(string projectref, string workproductref, string Owner, Rally_Dekstop.TestCase tcnew)
        {
            try
            {
                RallyAPI_UserStory.TestCase testCase = new Rally_Dekstop.RallyAPI_UserStory.TestCase();
                testCase.Name = tcnew.Name;
                testCase.Description = tcnew.Description;
                testCase.Notes = tcnew.Notes;
                testCase.Owner = Owner;
                testCase.Objective = tcnew.Objective;
                testCase.Type = tcnew.Type;
                testCase.Method = tcnew.Method;
                testCase.Priority = tcnew.Priority;
                testCase.Risk = tcnew.Risk;
                testCase.Package = tcnew.Package;
                testCase.PreConditions = tcnew.PreConditions;
                testCase.PostConditions = tcnew.PostConditions;
                testCase.ValidationInput = tcnew.ValidationInput;
                testCase.ValidationExpectedResult = tcnew.ValidationExpectedResult;
                
                RallyAPI_UserStory.Workspace ws = new Rally_Dekstop.RallyAPI_UserStory.Workspace();
                ws.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                testCase.Workspace = ws;

                RallyAPI_UserStory.Project ProjS = new Rally_Dekstop.RallyAPI_UserStory.Project();
                ProjS.@ref = projectref;
                testCase.Project = ProjS;


                //set ref to workproduct
                RallyAPI_UserStory.Artifact wk = new RallyAPI_UserStory.Artifact();
                wk.@ref = workproductref;
                testCase.WorkProduct = wk;
                
                RallyAPI_UserStory.CreateResult createResult = service.create(testCase);

                if (createResult.Errors.Length > 0)
                    return createResult.Errors[0];
                else
                    return string.Empty;

                
            }
            catch (Exception ee)
            {
                return ee.Message;

            }
        }
        public ArrayList GetDefects(string queryString)
        {
            try
            {
                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "defect";


                //string queryString = "(Owner = \"" + RallyDesk.Username + "\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                ArrayList result = new ArrayList();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            Defect defect = new Defect();

                            defect.ID = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).FormattedID;
                            defect.Owner = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Owner;
                            defect.Name = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Name;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Notes;
                            defect.Resolution = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Resolution;
                            defect.Severity = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Severity;
                            defect.Priority = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Priority;
                            defect.State = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).State;
                            defect.SubmittedBy = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).SubmittedBy;
                            defect.VerifiedIn = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).VerifiedInBuild;
                            defect.Environment = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Environment;
                            defect.ReleaseNote = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).ReleaseNote;
                            defect.Description = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Description;                            
                            defect.DefectRef = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).ObjectID.ToString();

                            defect.Project = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Project.@ref;

                            if (((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Requirement != null)
                            {
                                
                                    defect.Requirement.Name = ((Rally_Dekstop.RallyAPI_UserStory.WSObject)(((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Requirement)).refObjectName;
                                    defect.Requirement.Reference = ((Rally_Dekstop.RallyAPI_UserStory.WSObject)(((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Requirement)).@ref;
                                
                            
                            }
                            defect.TargetBuild = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetBuild;

                            if (((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetDate != null)
                                defect.TargetDate = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetDate.ToString();

                            defect.TargetDate = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetDate.ToString();
                            defect.FixedIn = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).FixedInBuild;
                            defect.FoundIn = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).FoundInBuild;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Notes;
                            defect.RevisionHistoryID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UserStory.WSObject)((((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i]))).RevisionHistory)).@ref);

                            if (((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments[j].@ref;
                                    defect.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }

                            result.Add(defect);
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public ArrayList UpdatedDefects(string timestamp)
        {
            try
            {
                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "defect";


                string queryString = "((LastUpdateDate >= \"" + timestamp + "\") or (CreationDate >= \"" + timestamp + "\")) ";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                ArrayList result = new ArrayList();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;
                
                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            Defect defect = new Defect();

                            defect.ID = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).FormattedID;
                            defect.Owner = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Owner;
                            defect.Name = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Name;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Notes;
                            defect.Resolution = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Resolution;
                            defect.Severity = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Severity;
                            defect.Priority = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Priority;
                            defect.State = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).State;
                            defect.SubmittedBy = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).SubmittedBy;
                            defect.VerifiedIn = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).VerifiedInBuild;
                            defect.Environment = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Environment;
                            defect.ReleaseNote = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).ReleaseNote;
                            defect.Description = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Description;
                            defect.DefectRef = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).ObjectID.ToString();

                            defect.Project = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Project.@ref;
                            if (((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Requirement != null)
                            {

                                defect.Requirement.Name = ((Rally_Dekstop.RallyAPI_UserStory.WSObject)(((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Requirement)).refObjectName;
                                defect.Requirement.Reference = ((Rally_Dekstop.RallyAPI_UserStory.WSObject)(((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Requirement)).@ref;
                               
                            }
                            defect.TargetBuild = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetBuild;

                            if (((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetDate != null)
                                defect.TargetDate = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetDate.ToString();

                            defect.TargetDate = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).TargetDate.ToString();
                            defect.FixedIn = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).FixedInBuild;
                            defect.FoundIn = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).FoundInBuild;
                            defect.Notes = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Notes;
                            defect.RevisionHistoryID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UserStory.WSObject)((((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i]))).RevisionHistory)).@ref);

                            if (((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UserStory.Defect)(queryResult.Results[i])).Attachments[j].@ref;
                                    defect.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }
                            result.Add(defect);
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public byte[] GetAttachmentFromObjectID(string objectID)
        {
            RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UserStory.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UserStory.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/attachment/" + objectID;

            RallyAPI_UserStory.WSObject attachment = service.read(persisTableObj);

            return ((RallyAPI_UserStory.Attachment)attachment).Content.Content;
        }
        public Hashtable GetTasks(string queryString)
        {
            try
            {
                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "task";


                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                Hashtable result = new Hashtable();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            Task tsk = new Task();
                            tsk.ID = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).FormattedID;
                            tsk.Owner = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Owner;
                            tsk.Name = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Name;
                            tsk.Notes = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Notes;
                            tsk.Actuals = Convert.ToString(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Actuals);
                            tsk.Blocked = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Blocked;
                            tsk.Description = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Description;
                            tsk.Estimate = Convert.ToString(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Estimate);
                            tsk.Project = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Project.@ref;
                            tsk.State = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).State;
                            tsk.StoryCard = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).WorkProduct.@ref;
                            tsk.ToDO = Convert.ToString(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).ToDo);
                            tsk.TaskRef = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).@ref;

                            if (((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments[j].@ref;
                                    tsk.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }
                            result.Add(tsk.ID, tsk);
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public Hashtable UpdatedTasks(string timestamp)
        {
            try
            {
                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "task";

                string queryString = "(LastUpdateDate >= \"" + timestamp + "\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;


                Hashtable result = new Hashtable();
                int i = 0;
                int resindex = 0;
                int querytimes = 1;
                int listEntrytill = 0;

                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  resindex + 1, pageSize);

                if (queryResult.TotalResultCount > 0 && queryResult.Results.Length > 0)
                {
                    listEntrytill = Convert.ToInt32(queryResult.TotalResultCount);
                    if (queryResult.TotalResultCount > pageSize)
                    {
                        querytimes = Convert.ToInt32(queryResult.TotalResultCount / pageSize);
                        querytimes = querytimes + 1;
                        listEntrytill = Convert.ToInt32(pageSize);

                    }

                    while (querytimes >= 1)
                    {
                        for (i = 0; i < listEntrytill; i++)
                        {
                            Task tsk = new Task();
                            tsk.ID = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).FormattedID;
                            tsk.Owner = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Owner;
                            tsk.Name = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Name;
                            tsk.Notes = ((Rally_Dekstop.RallyAPI_UserStory.Artifact)(queryResult.Results[i])).Notes;
                            tsk.Actuals = Convert.ToString(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Actuals);
                            tsk.Blocked = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Blocked;
                            tsk.Description = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Description;
                            tsk.Estimate = Convert.ToString(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Estimate);
                            tsk.Project = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Project.@ref;
                            tsk.State = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).State;
                            tsk.StoryCard = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).WorkProduct.@ref;
                            tsk.ToDO = Convert.ToString(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).ToDo);
                            tsk.TaskRef = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).@ref;

                            if (((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments.Length > 0)
                            {
                                for (int j = 0; j < ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments.Length; j++)
                                {
                                    Attachment attachmentRallyDesk = new Attachment();
                                    attachmentRallyDesk.ObjectID = System.IO.Path.GetFileName(((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments[j].@ref);
                                    attachmentRallyDesk.AttachmentName = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments[j].refObjectName;
                                    attachmentRallyDesk.XMLWebString = ((Rally_Dekstop.RallyAPI_UserStory.Task)(queryResult.Results[i])).Attachments[j].@ref;
                                    tsk.AttachmentList.Add(attachmentRallyDesk);

                                }
                            }
                            result.Add(tsk.ID, tsk);
                            resindex++;

                        }



                        queryResult = service.query(
                        workspace,
                        objectType,
                        queryString, orderString,
                        fetchFullObjects,
                        resindex + 1, pageSize);

                        querytimes--;
                        if (querytimes > 1)
                            listEntrytill = Convert.ToInt32(pageSize);
                        else
                            listEntrytill = Convert.ToInt32(queryResult.TotalResultCount) - resindex;
                    }


                }

                return result;
            }
            catch (Exception)
            {
                return null;

            }
        }
        public string UpdateDefect(Defect defect)
        {
            RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UserStory.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UserStory.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/defect/" + defect.DefectRef;

            RallyAPI_UserStory.WSObject currentDefect = service.read(persisTableObj);

            ((RallyAPI_UserStory.Defect)currentDefect).Name = defect.Name;
            ((RallyAPI_UserStory.Defect)currentDefect).Notes = defect.Notes;
            ((RallyAPI_UserStory.Defect)currentDefect).Owner = defect.Owner;
            ((RallyAPI_UserStory.Defect)currentDefect).ReleaseNote = defect.ReleaseNote;

            //if(((RallyAPI_UserStory.Defect)currentDefect).Requirement != null)
            //((RallyAPI_UserStory.Defect)currentDefect).Requirement.@ref = defect.Requirement.Reference;

            ((RallyAPI_UserStory.Defect)currentDefect).Resolution = defect.Resolution;
            ((RallyAPI_UserStory.Defect)currentDefect).Severity = defect.Severity;
            ((RallyAPI_UserStory.Defect)currentDefect).Priority = defect.Priority;
            ((RallyAPI_UserStory.Defect)currentDefect).State = defect.State;
            ((RallyAPI_UserStory.Defect)currentDefect).SubmittedBy = defect.SubmittedBy;
            ((RallyAPI_UserStory.Defect)currentDefect).TargetBuild = defect.TargetBuild;
            ((RallyAPI_UserStory.Defect)currentDefect).Description = defect.Description;
            ((RallyAPI_UserStory.Defect)currentDefect).Environment = defect.Environment;
            ((RallyAPI_UserStory.Defect)currentDefect).FixedInBuild = defect.FixedIn;
            ((RallyAPI_UserStory.Defect)currentDefect).FoundInBuild = defect.FoundIn;

            
            RallyAPI_UserStory.OperationResult result = service.update((RallyAPI_UserStory.PersistableObject)currentDefect);
            StringBuilder resultString = new StringBuilder();

            if (result.Errors.Length > 0)
            {
                resultString.Append(System.Environment.NewLine);
                foreach (string str in result.Errors)
                {
                    resultString.Append(str);
                    resultString.Append(System.Environment.NewLine);
                }
            }


            return resultString.ToString();

        }
        public void UpdateTask(Task task)
        {
            RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UserStory.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UserStory.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/defect/" + task.TaskRef;

            RallyAPI_UserStory.WSObject currentTask = service.read(persisTableObj);

            ((RallyAPI_UserStory.Task)currentTask).Name = task.Name;
            ((RallyAPI_UserStory.Task)currentTask).Notes = task.Notes;
            ((RallyAPI_UserStory.Task)currentTask).Owner = task.Owner;
            ((RallyAPI_UserStory.Task)currentTask).State = task.State;
            ((RallyAPI_UserStory.Task)currentTask).ToDo = Convert.ToDouble(task.ToDO);
            ((RallyAPI_UserStory.Task)currentTask).Actuals = Convert.ToDouble(task.Actuals);
            ((RallyAPI_UserStory.Task)currentTask).Blocked = task.Blocked;
            ((RallyAPI_UserStory.Task)currentTask).Description = task.Description;
            ((RallyAPI_UserStory.Task)currentTask).Estimate = Convert.ToDouble(task.Estimate);

            service.update((RallyAPI_UserStory.PersistableObject)currentTask);

        }
        public string GetRevisions(string objectID)
        {
            string htmlRevisionsText = "<html> <font size=\"3\" face=\"Calibri\">";
            RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UserStory.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UserStory.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/revisionhistory/" + objectID;

            RallyAPI_UserStory.WSObject currentRevisionHistory = service.read(persisTableObj);

            for (int i = ((RallyAPI_UserStory.RevisionHistory)currentRevisionHistory).Revisions.Length - 1; i >= 0; i--)
            {
                htmlRevisionsText = htmlRevisionsText + " <p> " + ((RallyAPI_UserStory.RevisionHistory)currentRevisionHistory).Revisions[i].Description + "<b> [ " + ((RallyAPI_UserStory.RevisionHistory)currentRevisionHistory).Revisions[i].User + " ] </b>" + " </p> ";
            }

            htmlRevisionsText = htmlRevisionsText + " </font></html>";
            return htmlRevisionsText;

        }
        public int ReturnNumberOfDefectsReOpened(string timestamp)
        {
            try
            {
                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "revision";

                string queryString = "(((CreationDate > \"" + timestamp + "\") and (Description contains \"to [Re-Open]\")) and (User = \"" + RallyDesk.Username + "\"))";

                //string queryString = "(LastUpdateDate >= \"" + timestamp + "\")";
                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;

                int result;
                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                  1, pageSize);

                result = queryResult.Results.Length;




                return result;
            }
            catch (Exception)
            {
                return -1;

            }
        }
        public int ReturnNumberOfDefectsReported(string timestamp)
        {
            try
            {
                RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
                workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                string objectType = "defect";

                string queryString = "((CreationDate > \"" + timestamp + "\") and (SubmittedBy = \"" + RallyDesk.Username + "\"))";


                string orderString = "CreationDate desc";

                bool fetchFullObjects = true;

                // paging information

                long pageSize = 100;

                int result = 0;
                // issue query
                RallyAPI_UserStory.QueryResult queryResult = service.query(
                  workspace,
                  objectType,
                  queryString, orderString,
                  fetchFullObjects,
                   1, pageSize);

                result = queryResult.Results.Length;





                return result;
            }
            catch (Exception)
            {
                return -1;

            }
        }

        public string CreateDefect(Defect defect)
        {
            RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UserStory.Project project = new Rally_Dekstop.RallyAPI_UserStory.Project();
            project.@ref = RallyDesk.CURRENTWORKSPACE.SelectedProjectRef;

            RallyAPI_UserStory.Defect currentDefect = new Rally_Dekstop.RallyAPI_UserStory.Defect();

            currentDefect.Workspace = workspace;
            currentDefect.Project = project;



            

            ((RallyAPI_UserStory.Defect)currentDefect).Name = defect.Name;
            ((RallyAPI_UserStory.Defect)currentDefect).Notes = defect.Notes;
            ((RallyAPI_UserStory.Defect)currentDefect).Owner = defect.Owner;
            ((RallyAPI_UserStory.Defect)currentDefect).ReleaseNote = defect.ReleaseNote;

            if (!string.IsNullOrEmpty(defect.Requirement.Reference))
                ((RallyAPI_UserStory.Defect)currentDefect).Requirement.@ref = defect.Requirement.Reference;

            ((RallyAPI_UserStory.Defect)currentDefect).Resolution = defect.Resolution;
            ((RallyAPI_UserStory.Defect)currentDefect).Severity = defect.Severity;
            ((RallyAPI_UserStory.Defect)currentDefect).Priority = defect.Priority;
            ((RallyAPI_UserStory.Defect)currentDefect).State = defect.State;
            ((RallyAPI_UserStory.Defect)currentDefect).SubmittedBy = defect.SubmittedBy;
            ((RallyAPI_UserStory.Defect)currentDefect).TargetBuild = defect.TargetBuild;
            ((RallyAPI_UserStory.Defect)currentDefect).Description = defect.Description;
            ((RallyAPI_UserStory.Defect)currentDefect).Environment = defect.Environment;
            ((RallyAPI_UserStory.Defect)currentDefect).FixedInBuild = defect.FixedIn;
            ((RallyAPI_UserStory.Defect)currentDefect).FoundInBuild = defect.FoundIn;

            RallyAPI_UserStory.CreateResult result = service.create((RallyAPI_UserStory.PersistableObject)currentDefect);


            StringBuilder resultString = new StringBuilder();

            if (result.Errors.Length > 0)
            {
                resultString.Append(System.Environment.NewLine);
                foreach (string str in result.Errors)
                {
                    resultString.Append(str);
                    resultString.Append(System.Environment.NewLine);                    
                }
            }
           

            return resultString.ToString();


        }
        public string UpdateTestCase(TestCase tc)
        {
            if (tc.TestRef == string.Empty)
            {
                tc.TestRef = GetReference("testcase", tc.ID);
            }
            RallyAPI_UserStory.Workspace workspace = new RallyAPI_UserStory.Workspace();
            workspace.@ref = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;

            RallyAPI_UserStory.PersistableObject persisTableObj = new Rally_Dekstop.RallyAPI_UserStory.PersistableObject();
            persisTableObj.@ref = "https://" + RallyDesk.HOSTNAME + ".rallydev.com/slm/webservice/1.05/testcase/" + tc.TestRef;

            RallyAPI_UserStory.WSObject currentTestCase = service.read(persisTableObj);

            ((RallyAPI_UserStory.TestCase)currentTestCase).Name = tc.Name;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Notes = tc.Notes;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Objective = tc.Objective;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Type = tc.Type;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Method = tc.Method;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Priority = tc.Priority;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Risk = tc.Risk;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Package = tc.Package;
            ((RallyAPI_UserStory.TestCase)currentTestCase).PreConditions = tc.PreConditions;
            ((RallyAPI_UserStory.TestCase)currentTestCase).PostConditions = tc.PostConditions;
            ((RallyAPI_UserStory.TestCase)currentTestCase).Description = tc.Description;
            
            ((RallyAPI_UserStory.TestCase)currentTestCase).ValidationInput = tc.ValidationInput;
            ((RallyAPI_UserStory.TestCase)currentTestCase).ValidationExpectedResult = tc.ValidationExpectedResult;

            RallyAPI_UserStory.OperationResult result = service.update((RallyAPI_UserStory.PersistableObject)currentTestCase);
            StringBuilder resultString = new StringBuilder();

            if (result.Errors.Length > 0)
            {
                resultString.Append(System.Environment.NewLine);
                foreach (string str in result.Errors)
                {
                    resultString.Append(str);
                    resultString.Append(System.Environment.NewLine);
                }
            }


            return resultString.ToString();


        }
    }
}
